package com.example.howard.picview.Tab1Fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.howard.picview.MyAdapter;
import com.example.howard.picview.MyApplication;
import com.example.howard.picview.PicView.PicViewActivity;
import com.example.howard.picview.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Howard on 2016/8/17.
 */
public class Tab1Fragment extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener,View.OnClickListener {
    public List<Map<String, Object>> imagedata = new ArrayList<>();
    public List<String> ImagePath = new ArrayList<>();
    public List<String> creattime =new ArrayList<>();
//    public GetImageDate getImageDate;

    public MyAdapter myAdapter;
    public GridView gridView;
    public MyApplication myApplication;
    private ArrayList<Boolean> selectItems;
    private Button btnCancel, btnDel, btnSelectAll, btnClear;
    private CheckBox box;
    private RelativeLayout headerLayout;
    private TextView numText;
    public boolean isState;
    private ActionBar actionBar;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab1, null);

        gridView= (GridView) view.findViewById(R.id.allPicView);
        numText = (TextView) view.findViewById(R.id.number);
        btnCancel = (Button) view.findViewById(R.id.btn_cancel);
        btnDel = (Button) view.findViewById(R.id.btn_del);
        btnSelectAll = (Button) view.findViewById(R.id.btn_select_all);
        btnClear = (Button) view.findViewById(R.id.btn_clear);
        btnCancel.setOnClickListener(this);
        btnDel.setOnClickListener(this);
        btnSelectAll.setOnClickListener(this);
        btnClear.setOnClickListener(this);
        headerLayout = (RelativeLayout) view.findViewById(R.id.header);
        selectItems = new ArrayList<>();
//        imagedata=getImageDate.getImageFiles(getContext());
        myApplication= (MyApplication) getActivity().getApplication();
        myApplication.setTab1Fragment(this);
        gridView.setOnItemClickListener(this);
        gridView.setOnItemLongClickListener(this);
        imagedata=myApplication.imagedata;
//        Collections.reverse(imagedata);
        ImagePath=getImagepath();
        creattime=getImagetime();
        setRecyclerViewAdapter();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        myApplication.setSelectItems(selectItems);
        myApplication.setShowimage(ImagePath);
    }


    private List<String> getImagepath(){
        int i;
        List<String> pathlist=new ArrayList<>();
        for (i=0;i<imagedata.size();i++){
            pathlist.add(imagedata.get(i).get("URL").toString());
        }
        return pathlist;
    }

    private List<String> getImagetime(){
        int j;
        List<String> timelist=new ArrayList<>();
        for (j=0;j<imagedata.size();j++){
            timelist.add(imagedata.get(j).get("TIME").toString().substring(0,10));
        }
        return timelist;
    }



    private void setRecyclerViewAdapter(){
        myAdapter = new MyAdapter(ImagePath,creattime,getContext(),myApplication);
        gridView.setVerticalScrollBarEnabled(true);
        gridView.setAdapter(myAdapter);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        if (isState) {
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.check_box);
            if (checkBox.isChecked()) {
                checkBox.setChecked(false);
                selectItems.set(i, false);
            } else {
                checkBox.setChecked(true);
                selectItems.set(i, true);
            }
            myAdapter.notifyDataSetChanged();
            myApplication.setSelectItems(selectItems);
            setSelectNum();
        }else {
            Context context=getContext();
            Intent intent =new Intent();
            intent.setClass(context,PicViewActivity.class);
            intent.putExtra("pos",i);
            startActivity(intent);
        }


    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
        if (!isState) {
            box = (CheckBox) view.findViewById(R.id.check_box);
            selectItems = new ArrayList<>();
            int j;
            for (j = 0; j < ImagePath.size(); j++) {
                selectItems.add(false);
            }
            selectItems.set(i, true);
            myApplication.setSelectItems(selectItems);
            setState(true);
            myAdapter.setIsState(true);
            setSelectNum();
        }

        return true;
    }





    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel :
                selectItems.clear();
                myApplication.setSelectItems(selectItems);
                numText.setText("已选择0项");
                myAdapter.setIsState(false);
                setState(false);
                break;
            case R.id.btn_clear :
                setSelectAll(false);
                myApplication.setSelectItems(selectItems);
                break;
            case R.id.btn_select_all:
                setSelectAll(true);
                myApplication.setSelectItems(selectItems);
                break;
            case R.id.btn_del:
                delSelections();
                break;
        }
    }

    //设置当前状态 是否在多选模式
    private void setState(boolean b) {
        isState = b;
        myApplication.setTab1Fragment(this);
        if (b) {
            headerLayout.setVisibility(View.VISIBLE);
            btnDel.setVisibility(View.VISIBLE);

        } else {
            headerLayout.setVisibility(View.GONE);
            btnDel.setVisibility(View.GONE);
        }
    }

    //显示已选项数目
    private void setSelectNum() {
        int num = 0;
        for (Boolean b : selectItems) {
            if (b)
                num ++;
        }
        numText.setText("已选择" + num + "项");
    }

    //全选
    private void setSelectAll(boolean b) {
        for (int i = 0; i < selectItems.size(); i++) {
            selectItems.set(i, b);
            myAdapter.notifyDataSetChanged();
            setSelectNum();
        }
        myApplication.setSelectItems(selectItems);
        btnSelectAll.setVisibility(b? View.GONE : View.VISIBLE);
        btnClear.setVisibility(b ? View.VISIBLE : View.GONE);
    }

    //删除
    private void delSelections() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        if (!selectItems.contains(true)) {
            builder.setTitle("提示").setMessage("当前未选中项目").setPositiveButton("确认", null).create().show();
        } else {
            builder.setTitle("提示");
            builder.setMessage("确认删除所选项目？");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    List<String> pathlist=new ArrayList<String>();

                    for (int i = 0; i < ImagePath.size(); i++) {
                        if (selectItems.get(i)) {
                            pathlist.add(ImagePath.get(i));
                            ImagePath.set(i, null);
                            creattime.set(i,null);
                        }
                    }
                    if (pathlist.size()!=0){
                        for (int j=0;j<pathlist.size();j++){
                            File removePic = new File(pathlist.get(j));
                            removePic.delete();
                            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            Uri uri = Uri.fromFile(removePic);
                            intent.setData(uri);
                            getContext().sendBroadcast(intent);
                        }

                    }
                    while (ImagePath.contains(null)) {
                        ImagePath.remove(null);
                        creattime.remove(null);
                    }
                    selectItems = new ArrayList<>();
                    for (int i = 0; i < ImagePath.size(); i++) {
                        selectItems.add(false);
                    }

                    myAdapter.setData(ImagePath,creattime);
                    myAdapter.notifyDataSetChanged();

                    myAdapter.setIsState(false);
                    setState(false);

                }
            });
            builder.setNegativeButton("取消", null);
            builder.create().show();
        }

    }
    public void setKeyDown(){

        selectItems.clear();
        myApplication.setSelectItems(selectItems);

        myAdapter.setIsState(false);
        setState(false);
    }



}
